﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using System.Net.Http;
using System.Net.Http.Headers;
using Newtonsoft.Json;
using Newtonsoft.Json.Linq;

namespace Mes.BOM管理.Model
{
	public partial class BOMCreate : Form
	{
		private readonly HttpClient httpClient = new HttpClient();
		private const string CreateUrl = "http://10.223.8.10:8000/BOM/api/BOM/BOMCreate";

		public BOMCreate()
		{
            InitializeComponent();
            txtNumber.Text = DateTime.Now.ToString("yyyyMMddHHmmss");
        }

		private void btnAddRow_Click(object sender, EventArgs e)
		{
			this.dgvIngredients.Rows.Add();
		}

		private async void btnSave_Click(object sender, EventArgs e)
		{
			try
			{
				// 确保表格编辑内容先提交到单元格
				this.Validate();
				this.dgvIngredients.EndEdit();
				if (this.dgvIngredients.CurrentCell != null)
				{
					this.dgvIngredients.CommitEdit(DataGridViewDataErrorContexts.Commit);
				}
				// 读取基本信息
				var product = new
				{
					Id = 0,
					CreateId = 0,
					CreateTime = this.dtpCreateTime.Value.ToString("yyyy-MM-ddTHH:mm:ss.fffZ"),
					UpdateId = 0,
					UpdateTime = this.dtpCreateTime.Value.ToString("yyyy-MM-ddTHH:mm:ss.fffZ"),
					Deleted = 0,
					DeleteTime = this.dtpCreateTime.Value.ToString("yyyy-MM-ddTHH:mm:ss.fffZ"),
					IsDeleted = false,
					Number = this.txtNumber.Text.Trim(),
					ProductNumber = this.txtProductNumber.Text.Trim(),
					ProductName = this.txtProductName.Text.Trim(),
					Model = this.txtModel.Text.Trim(),
					Size = this.txtSize.Text.Trim(),
					Operator = "",
					Version = this.txtVersion.Text.Trim()
				};

				// 读取原料表
				var ingredient = new List<object>();
				for (int i = 0; i < this.dgvIngredients.Rows.Count; i++)
				{
					var row = this.dgvIngredients.Rows[i];
					if (row.IsNewRow) continue;
					string num = Convert.ToString(row.Cells["colNumber"].Value);
					string name = Convert.ToString(row.Cells["colIngredientName"].Value);
					string model = Convert.ToString(row.Cells["colIModel"].Value);
					string size = Convert.ToString(row.Cells["colISize"].Value);
					string unit = Convert.ToString(row.Cells["colUnit"].Value);
					int qty = 0; int.TryParse(Convert.ToString(row.Cells["colIngredientNum"].Value), out qty);
					if (string.IsNullOrEmpty(num) && string.IsNullOrEmpty(name)) continue;
					ingredient.Add(new
					{
						Id = 0,
						CreateId = 0,
						CreateTime = this.dtpCreateTime.Value.ToString("yyyy-MM-ddTHH:mm:ss.fffZ"),
						UpdateId = 0,
						UpdateTime = this.dtpCreateTime.Value.ToString("yyyy-MM-ddTHH:mm:ss.fffZ"),
						Deleted = 0,
						DeleteTime = this.dtpCreateTime.Value.ToString("yyyy-MM-ddTHH:mm:ss.fffZ"),
						IsDeleted = false,
						PId = 0,
						Number = num,
						IngredientName = name,
						Model = model,
						Size = size,
						Unit = unit,
						IngredientNum = qty
					});
				}

				if (ingredient.Count == 0)
				{
					MessageBox.Show("请至少添加一条原料明细");
					return;
				}

				var payload = new { product = product, ingredient = ingredient };

				// 使用 HttpClientHelper 发送 POST 请求，获取原始JSON
				string jsonData = JsonConvert.SerializeObject(payload);
				var content = new StringContent(jsonData, Encoding.UTF8, "application/json");
				string result = await Mes.HttpClientHelper.ClientAsync("POST", CreateUrl, isAuthorzation: !string.IsNullOrEmpty(Mes.login.CurrentToken), content: content);
				if (string.IsNullOrWhiteSpace(result))
				{
					MessageBox.Show("添加失败：服务器无响应或返回为空");
					return;
				}
				try
				{
					var jo = JObject.Parse(result);
					int code = jo["Code"]?.Value<int>() ?? jo["code"]?.Value<int>() ?? 0;
					string msg = jo["Message"]?.ToString() ?? jo["message"]?.ToString() ?? "";
					if (code == 200)
					{
						MessageBox.Show(string.IsNullOrEmpty(msg) ? "添加成功" : msg);
						this.DialogResult = DialogResult.OK;
						this.Close();
					}
					else
					{
						MessageBox.Show(string.IsNullOrEmpty(msg) ? ($"添加失败：Code={code}") : ($"添加失败：{msg}"));
					}
				}
				catch
				{
					// 如果不是对象JSON，也认为成功
					MessageBox.Show("添加成功");
					this.DialogResult = DialogResult.OK;
					this.Close();
				}
			}
			catch (Exception ex)
			{
				MessageBox.Show("添加异常: " + ex.Message);
			}
		}
    }
}
